//
//  LDPushOrderViewController.m
//  dmao-customer
//
//  Created by macbook on 2017/10/17.
//  Copyright © 2017年 秦慕乔. All rights reserved.
//

#import "LDPushOrderViewController.h"
#import "LDPayTableViewCell.h"
#import "ZSDPaymentForm.h"
#import "ZSDPaymentView.h"

@interface LDPushOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSDictionary *_payData;
    NSMutableArray *_dataArr;
    NSArray *_IconArr;
    NSString *_payType;
}
@property (weak, nonatomic) IBOutlet UILabel *MoneyLabel;
@property (strong, nonatomic) UITableView * tableView;
@property (strong, nonatomic) UIView *footerView;
@property (copy, nonatomic) NSString *userMo;
@property (copy, nonatomic) NSString *data;
@property (weak, nonatomic) IBOutlet UIButton *PayBtn;
@property (strong, nonatomic) LDPayTableViewCell*cell;
@end

@implementation LDPushOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"提交订单";
    _dataArr = [NSMutableArray array];
    _IconArr = [[NSArray alloc] initWithObjects:@"AliPay",@"WeixinPay",@"LDPayBalance",@"LineDown",@"LineDown",nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPassword:) name:@"GetPassword" object:nil];
    _PayBtn.enabled = NO;
    _MoneyLabel.text = [NSString stringWithFormat:@"%.2f", [self.money floatValue]];
    if (self.isLineOnOrder) {
        [self downloadLOData];
    }else{
        [self downloadLDData];
    }
    
    [self createFooterView];
    [self createTableView];
}

- (void)downloadLOData
{
    [self.view loadingOnAnyView];
    [THWManager PostHttp:API(LOChoosePay) Parameters:@{@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        [self.view removeAnyView];
        for (NSDictionary *d in (NSArray*)responseObject[@"data"]) {
            if ([d[@"payCode"]isEqual:@"wallets"]) {
                _userMo = d[@"userMoney"];
                
            }
            [_dataArr addObject:d];
        }
        [_tableView reloadData];
        
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
        
    }];
}
- (void)downloadLDData
{
    [self.view loadingOnAnyView];
    [THWManager PostHttp:API(LDSubmitOrder) Parameters:@{@"type":@"1",@"lineId":self.lineId,@"money":self.money,@"userToken":[Utils getUserToken]} Success:^(id responseObject) {
        [self.view removeAnyView];
        if ([String(responseObject[@"status"]) isEqualToString:@"-1"]) {
            _cell.BalanceLabel.hidden = YES;
            _cell.chooseBtn.enabled = NO;
            [self.view Message:responseObject[@"msg"]];
        }else{
            _data = responseObject[@"data"];
            _userMo = responseObject[@"userMoney"];
            for (NSDictionary *d in responseObject[@"payList"]) {
                if ([d[@"payCode"]isEqual:@"wallets"]) {
                    [_dataArr addObject:d];
                }

            }
            [_tableView reloadData];
        }
        
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

- (void)createFooterView
{
    _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
    _footerView.backgroundColor = RGB(232, 234, 234);
}

- (void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 164, WIDTH, HEIGHT-164-49)];
    //    space = [[QQSpaceView alloc] initWithFrame:_tableView.frame];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"LDPayTableViewCell" bundle:nil] forCellReuseIdentifier:@"LDPayTableViewCell"];
    [_tableView setTableFooterView:_footerView];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (NSMutableAttributedString*)showLeft:(NSString *)left
{
    NSString *content = [NSString stringWithFormat:@"(剩余：%@)", left];
    NSArray *number = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    NSMutableAttributedString *attributeString  = [[NSMutableAttributedString alloc]initWithString:content];
    for (int i = 0; i < content.length; i ++) {
        //这里的小技巧，每次只截取一个字符的范围
        NSString *a = [content substringWithRange:NSMakeRange(i, 1)];
        //判断装有0-9的字符串的数字数组是否包含截取字符串出来的单个字符，从而筛选出符合要求的数字字符的范围NSMakeRange
        if ([number containsObject:a]) {
            [attributeString setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:12],NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleNone]} range:NSMakeRange(i, 1)];
        }
    }
    return attributeString;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   LDPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LDPayTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = _dataArr[indexPath.row];
    
    cell.TypeName.text = dic[@"payName"];
    [cell.IconImg setImage:[UIImage imageNamed:_IconArr[indexPath.row]]];
    if (self.isLineOnOrder) {
        if ([dic[@"payCode"] isEqualToString:@"wallets"]) {
            cell.BalanceLabel.attributedText = [self showLeft:dic[@"userMoney"]];
        }else if ([dic[@"payCode"] isEqualToString:@"useraward"]) {
            cell.BalanceLabel.attributedText = [self showLeft:dic[@"userAward"]];
        }else{
            cell.BalanceLabel.text = @"";
        }
    }else{
        cell.BalanceLabel.attributedText = [self showLeft:_userMo];
    }
    
    __block LDPushOrderViewController *blockSelf = self;
    cell.select = ^{
        if (_cell) {
            [_cell changeUi:YES];
        }
        _cell = cell;
        _payType = dic[@"payCode"];
        [blockSelf.PayBtn setBackgroundColor:[UIColor redColor]];
        blockSelf.PayBtn.enabled = YES;
    };
    cell.remove = ^{
        [blockSelf.PayBtn setBackgroundColor:[UIColor lightGrayColor]];
        blockSelf.PayBtn.enabled = NO;
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (void)LOpayclick:(NSString*)url
{
    NSString *str = self.loOrdernum?self.loOrdernum:self.orderNo;
    NSDictionary *para = @{@"orderNo":str,@"isBatch":[self.type isEqualToString:@"order"]?@"0":@"1"};
    [THWManager PostHttp:url Parameters:para Success:^(id responseObject) {
        if ([responseObject[@"status_code"]integerValue]==1000) {
            
            //http://www.rmgs9.com/index.php/app/appwallets/payment
            [THWManager PostHttp:responseObject[@"data"][@"url"] Parameters:@{@"userToken":[Utils getUserToken],@"key":responseObject[@"data"][@"key"]} Success:^(id responseObject) {
//                {
//                    needPay = 17092;
//                    paykey = gKZ2rIN4paiAeHTcr6qnp4GpprCv241shXiZrA;
//                    userMoney = "0.00";
//                };
                _payData = responseObject[@"data"];
                [self showKeyboard];
            } andFalse:^(NSError *error) {
                
            }];
        }
    } andFalse:^(NSError *error) {
        
    }];
}
- (IBAction)PayClick:(UIButton *)sender {
    
    if ([_payType isEqualToString:@"wallets"]) {
        if (self.isLineOnOrder) {
            [self LOpayclick:API(LOGetwallet)];
        }else{
            [self showKeyboard];
        }
    }
    if([_payType isEqualToString:@"alipays"]){
        if (self.isLineOnOrder) {
            
        }else{
            
        }
    }
    if([_payType isEqualToString:@"weixinpays"]){
        if (self.isLineOnOrder) {
            
        }else{
            
        }
    }
    if([_payType isEqualToString:@"translates"]){
        if (self.isLineOnOrder) {
            
        }else{
            
        }
    }
    if([_payType isEqualToString:@"useraward"]){
        if (self.isLineOnOrder) {
            [self LOpayclick:API(LOGetuseraward)];
        }else{
            
        }
        
    }
    
}
- (void)showKeyboard
{
    ZSDPaymentView *payment = [[ZSDPaymentView alloc]init];
    payment.title = @"请输入支付密码";
    payment.goodsName = @"零钱";
    payment.amount = [self.money floatValue];
    [payment show];
}
//(
//{
//    payCode = alipays;
//    payName = "\U652f\U4ed8\U5b9d(\U53ca\U65f6\U5230\U5e10)";
//},
//{
//    payCode = weixinpays;
//    payName = "\U5fae\U4fe1\U652f\U4ed8";
//},
//{
//    payCode = wallets;
//    payName = "\U4f59\U989d\U652f\U4ed8";
//    userMoney = "1040.00";
//},
//{
//    payCode = translates;
//    payName = "\U7ebf\U4e0b\U8f6c\U8d26";
//},
//{
//    payCode = useraward;
//    payName = "\U4f63\U91d1\U8f6c\U8d26";
//    userAward = "60.05";
//}
// )
- (void)loPay:(NSNotification *)notice
{
    NSString *url;
    if([_payType isEqualToString:@"useraward"])
    {
        url = API(LOPayByUseraward);
    }else{
        url =API(LOPayByWallet);
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:nil];
    NSDictionary *para = @{@"userToken":[Utils getUserToken],@"payPwd":notice.object,@"key":_payData[@"paykey"],@"orderNo":self.loOrdernum?self.loOrdernum:self.orderNo,@"isBatch":[self.type isEqualToString:@"order"]?@"0":@"1"};
    [THWManager PostHttp:url Parameters:para Success:^(id responseObject) {
        [self.view Message:responseObject[@"msg"]];
        if ([responseObject[@"status_code"]integerValue]==1000) {
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            });
        }
    } andFalse:^(NSError *error) {
        
    }];
}
- (void)ldPay:(NSNotification *)notice
{
    if ([self.type isEqualToString:@"order"]) {
        //订单支付
        [self.view loadingOnAnyView];
        [THWManager PostHttp:API(LDBalancePayNext) Parameters:@{@"type":@"1", @"isBatch":@"0", @"orderNo":self.orderNo, @"userToken":[Utils getUserToken], @"payPwd":notice.object} Success:^(id responseObject) {
            [self.view removeAnyView];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:nil];
            [self.view Message:responseObject[@"msg"]];
            if ([String(responseObject[@"status"]) isEqualToString:@"1"]) {
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
                });
            }
            
        } andFalse:^(NSError *error) {
            [self.view removeAnyView];
        }];
    }else{
        [self.view loadingOnAnyView];
        //线下支付
        [THWManager PostHttp:API(LDBalancePay) Parameters:@{@"isBatch":@"1", @"orderNo":_data, @"userToken":[Utils getUserToken]} Success:^(id responseObject) {
            NSString *key = responseObject[@"data"][@"key"];
            [self PayNext:key andPSW:notice.object];
        } andFalse:^(NSError *error) {
            [self.view removeAnyView];
        }];
    }
}
- (void)getPassword:(NSNotification *)notice{
    
    if (self.isLineOnOrder) {
        [self loPay:notice];
    }else{
        [self ldPay:notice];
    }
}

- (void)PayNext:(NSString *)key andPSW:(NSString *)notice{
    [THWManager PostHttp:API(LDBalancePayNext) Parameters:@{@"type":@"1", @"key":key, @"userToken":[Utils getUserToken], @"payPwd":notice} Success:^(id responseObject) {
        [self.view removeAnyView];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:nil];
        [self.view Message:responseObject[@"msg"]];
        if ([String(responseObject[@"status"]) isEqualToString:@"1"]) {
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            });
        }
        
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
